#pragma once

#ifndef WIN32
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <execinfo.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>

static void ForkMySelf(const char* pszExeName, int seconds = 3)
{
	pid_t pid;
	
FORK_LOOP:    
	pid = fork();
	
	if(pid < -1)
	{
		fprintf(stdout, "\r\n%s create child process error.\r\n", pszExeName);
		exit(-1);
	}
	else if(pid > 0)
	{
		int nStatus;
		pid_t childPid;
		
		if((childPid = waitpid(pid, &nStatus, 0)) < 0)
			exit(-1);
		if(0 == nStatus)
			exit(-1);
		
		if(WIFSIGNALED(nStatus))
		{
			char szCoreFile[1024] = {0};
			fprintf(stdout, "\r\n\r\n%s child process quitted for signal %d, %s will create anther child process %d seconds later.\r\n\r\n", pszExeName, WTERMSIG(nStatus), pszExeName, seconds);
			sprintf(szCoreFile, "core.%d", pid);
			chmod(szCoreFile, 0666);
		}
		sleep(seconds);
		goto FORK_LOOP;
	}
}

#else
#include <windows.h>
#endif


static void MySleep(unsigned int dwMillionSecond)
{
#ifdef WIN32
	Sleep(dwMillionSecond);
#else
	usleep(dwMillionSecond*1000);
#endif
}


